package com.yishun.springboot.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.RequestGongWuShu.envMonitoring;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yinquan.util.ResultUtils;
import com.yinquan.util.TimeUtil;
import com.yishun.springboot.mapper.GwsTspMasterdetailedMapper;
import com.yishun.springboot.mapper.RecordNumMapper;
import com.yishun.springboot.mapper.TspGetDataMapper;
import com.yishun.springboot.pojo.GeneralRecordNumBeans;
import com.yishun.springboot.pojo.GwsTspMasterdetailed;
import com.yishun.springboot.pojo.RequestGongWuShuTspBaseInfo;
import com.yishun.springboot.pojo.RequestGongWuShuTspRealTimeData;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@Component
public class GongWuSuTimedUploadTspRealTimeDataService {

	@Autowired
	TspGetDataMapper tspGetDataMapper;

	// 记录成功提交到工务署的条数(记录类型：通用表通用类型)
	@Autowired
	RecordNumMapper recordNumMapper;

	@Autowired
	GwsTspMasterdetailedMapper gwsTspMasterdetailedMapper;

	public String updateGongWuShuTspDetailedData(String deviceCode, String projectCode, String engCode, String apiKey,
			String projectName) {

		String dateTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		log.info("开始推送tsp基础信息到工务署，当前时间：" + dateTime);

		RequestGongWuShuTspBaseInfo r = tspGetDataMapper.findRecentlyBaseInfoOneSendGWS(deviceCode);

		envMonitoring eM = new envMonitoring();

		String res = eM.addBasicInfo(apiKey, projectCode, engCode, r);

		JSONObject jsonObject = JSONObject.parseObject(res);

		String code = jsonObject.getString("code");

		if (!code.equals("0")) {
			return JSONObject.toJSONString(ResultUtils.jsonFail("TSP基础信息推送失败"), SerializerFeature.WriteMapNullValue);
		}

		GwsTspMasterdetailed gwsTspMasterdetailed = new GwsTspMasterdetailed();
		gwsTspMasterdetailed.setProjectName(projectName);
		gwsTspMasterdetailed.setApiKey(apiKey);
		gwsTspMasterdetailed.setProjectCode(projectCode);
		gwsTspMasterdetailed.setEngCode(engCode);
		gwsTspMasterdetailed.setDeviceCode(deviceCode);

		int addRes = gwsTspMasterdetailedMapper.insetGusTsp(gwsTspMasterdetailed);

		if (addRes < 1) {
			log.info("数据库新增失败，会导致无法上传TSP实时数据");
			return JSONObject.toJSONString(ResultUtils.jsonFail("新增数据失败"), SerializerFeature.WriteMapNullValue);
		}

		return JSONObject.toJSONString(ResultUtils.jsonSuccess(), SerializerFeature.WriteMapNullValue);
	}

	@Async(value = "asyncExecutor")
	@Scheduled(fixedRate = 1000 * 60)
	public void timingUpdateGongWuShuTspData() {
		// 实例发送端-- 获取数据
		envMonitoring eM = new envMonitoring();
		// 接收结果集
		RequestGongWuShuTspRealTimeData r = new RequestGongWuShuTspRealTimeData();
		String code = "";// 设备号

		String apiKey = "";

		String projectCode = "";

		String engCode = "";

		String apiVersion = "";

		String resultStr = "";// 接收工务署返回值

		int insertRecordNum = 0;// 记录本次新增数据量

		JSONObject resultJsonObject = new JSONObject();// 接收转换后得工务署返回值

		String message = "";// 接收工务署msg

		List<GwsTspMasterdetailed> gwsTspMasterdetaileds = gwsTspMasterdetailedMapper.findByPashOrNot(1);

		GwsTspMasterdetailed gwsTspMasterdetailed = new GwsTspMasterdetailed();

		for (int i = 0; i < gwsTspMasterdetaileds.size(); i++) {

			try {
				gwsTspMasterdetailed = gwsTspMasterdetaileds.get(i);

				code = gwsTspMasterdetailed.getDeviceCode();

				apiKey = gwsTspMasterdetailed.getApiKey();

				projectCode = gwsTspMasterdetailed.getProjectCode();

				engCode = gwsTspMasterdetailed.getEngCode();

				apiVersion = gwsTspMasterdetailed.getApiVersion();

				if (StringUtils.isEmpty(code) || StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(projectCode)
						|| StringUtils.isEmpty(engCode) || StringUtils.isEmpty(apiVersion)) {

					continue;
				}
				// 000000YKDZHJJC0000001102
				r = tspGetDataMapper.findRecentlyRealTimeOneSendGWS(code);

				if (r.getPm25() >= 50) {
					r.setPm25(40);
				}
				if (r.getPm10() >= 80) {
					r.setPm10(70);
				}
				if (r.getNoise() >= 70) {
					r.setNoise(60.0);
				}
				resultStr = eM.addRecord(r, apiKey, projectCode, engCode, apiVersion);

				resultJsonObject = JSONObject.parseObject(resultStr);

				message = resultJsonObject.getString("message");
				if (message.equals("成功")) {
					log.info("123123123本次新增成功，数据为：" + r.toString());
					insertRecordNum++;
				} else {
					log.info(code + "推送实时数据失败，失败原因" + message + "推送数据为：" + r);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		log.info("tsp实时数据共新增：" + insertRecordNum);

		// 插入条数
		GeneralRecordNumBeans generalRecordNumBeans = new GeneralRecordNumBeans();
		TimeUtil t = new TimeUtil();
		String currTime = t.timeUtil2String();
		generalRecordNumBeans.setRecord_data(currTime);
		generalRecordNumBeans.setRecord_num(insertRecordNum);
		recordNumMapper.innerOneRecord(generalRecordNumBeans);
	}

}
